package shuashuami.hb.com.http;

import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import shuashuami.hb.com.fragment.HbCUserFragm;
import shuashuami.hb.com.hbclient.R;
import shuashuami.hb.com.hdlibrary.util.ToastUtil;
import shuashuami.hb.com.share.ShareCUserInfo;
import shuashuami.hb.com.view.SignDialog;

/**
 * Created by Administrator on 2017/7/4.
 */

public class CSign {

    private HbCUserFragm activity;
    private TextView tvSign;

    public CSign(HbCUserFragm activity, TextView tvSign) {
        this.activity = activity;
        this.tvSign = tvSign;
    }

    public void getMessage() {
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                Message message = handler.obtainMessage(1);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };
        ShareCUserInfo shareCUserInfo = new ShareCUserInfo(activity.getActivity());
        HttpMethods.signC(listener,
                shareCUserInfo.getId()
        );
    }

    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {         // handle message
            switch (msg.what) {
                case 1:
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.getInt("status") == 203) {
                            LoginHttp loginHttp = new LoginHttp(activity.getActivity());
                            loginHttp.login();
                            return;
                        }
                        if (jsonObject.getInt("status") == 200) {
                            tvSign.setText("今日已签到");
                            tvSign.setBackgroundResource(R.drawable.shape_corner_user_level_press_bg);
                            activity.getUserInfo();
                            JSONObject temp = jsonObject.getJSONObject("content");
                            showSignDialog(temp.getString("exp"));
                        } else {
                            ToastUtil.showShort(activity.getActivity(), jsonObject.getString("message"));
                        }
                    } catch (JSONException e) {
                        ToastUtil.showShort(activity.getActivity(), "数据解析错误");
                    }


                    break;
            }

            super.handleMessage(msg);
        }
    };

    private void showSignDialog(String jingyan) {
        SignDialog signDialog = new SignDialog(activity.getActivity(), jingyan);
        signDialog.show();
    }

}
